import { reactive, ref, nextTick } from "vue";
import L, { type Map } from "leaflet";
import { mapConfig } from "@/config/map";
import HeatmapOverlay from "leaflet-heatmap";
import "leaflet.heat";
/**热力图配置 */
export interface HeatmapConfig {
  container?: HTMLElement;
  radius?: number;
  blur?: number;
  ggradient?: { [key: number]: string };
  opacity?: [number, number];
  minOpacity?: number;
  maxOpacity?: number;
  gradient?: object;
  max?: number;
  min?: number;
}
/**热力图数据列表 */
interface HeatmapData {
  /**维度 */
  lat: string | number;
  /**经度 */
  lng: string | number;
  /**值 */
  value: number;
}
export function useHeatmap(map: Map) {
  // 默认数据
  const heatmapVisible = ref(true);
  const _radius = ref(mapConfig.radius);
  const _blur = ref(mapConfig.blur);
  const initData = [{ lat: 39.9042, lng: 116.4074, value: 100 }];
  const config = reactive<HeatmapConfig>({
    radius: _radius.value,
    blur: _blur.value,
    maxOpacity: 0.8,
    gradient: {
      0.4: "blue",
      0.6: "lime",
      0.7: "yellow",
      1: "red"
    }
  });
  let heatmapLayer: L.HeatLayer | null = null;

  const create = (data: Array<HeatmapData>) => {
    if (!map.value) return;
    if (heatmapLayer) {
      map.value.removeLayer(heatmapLayer);
    }
    // 将数据转换为 leaflet.heat 所需的格式 [lat, lng, intensity]
    const convertedData = data.map(item => [
      item.lat,
      item.lng,
      item.value / 100
    ]);

    // 创建热力图层
    heatmapLayer = L.heatLayer(convertedData, {
      ...config,
      max: config.max ?? Math.max(...data.map(d => d[2])),
      min: config.min ?? Math.min(...data.map(d => d[2]))
    });
    if (heatmapVisible.value) {
      heatmapLayer.addTo(map.value);
    }
    return heatmapLayer;
  };
  const newCreate = async (data: Array<HeatmapData>) => {
    await nextTick();
    if (!map.value) return;
    if (heatmapLayer) {
      map.value.removeLayer(heatmapLayer);
    }
    // 创建热力图层
    heatmapLayer = new HeatmapOverlay({
      radius: 15,
      maxOpacity: 0.5,
      scaleRadius: true,
      useLocalExtrema: true,
      latField: "lat",
      lngField: "lng",
      valueField: "value"
    });
    // 将数据转换为 leaflet.heat 所需的格式 [lat, lng, intensity]
    const heatmapData = {
      data: data.map(item => ({
        lat: item.lat,
        lng: item.lng,
        value: item.value / Math.max(...data.map(d => d.value))
      }))
    };
    console.log(heatmapData);
    heatmapLayer.setData(heatmapData);
    console.log(heatmapLayer);
    console.log(map.value);
    if (heatmapVisible.value) {
      // heatmapLayer.addTo(map.value);
      map.value.addLayer(heatmapLayer);
    }
    return heatmapLayer;
  };
  const update = (heatmapLayer: L.HeatLayer, newData?: Array<HeatmapData>) => {
    if (!heatmapLayer) return;
    // 将数据转换为 leaflet.heat 所需的格式 [lat, lng, intensity]
    const convertedData = newData.map(item => [
      item.lat,
      item.lng,
      item.value / 100
    ]);
    // 设置图层数据前检查有效性
    if (convertedData.length > 0) {
      heatmapLayer.setLatLngs(convertedData);
    }
    // 安全计算最大最小值
    const values = convertedData.map(d => d[2]);
    const dataMax = values.length > 0 ? Math.max(...values.map(Number)) : 1;
    const dataMin = values.length > 0 ? Math.min(...values.map(Number)) : 0;
    // heatmapLayer.setOptions({
    //   min: dataMin ?? 0,
    //   max: dataMax ?? 1
    // });
    heatmapLayer.redraw();
  };
  const updateConfig = (
    heatmapLayer: L.HeatLayer,
    newConfig: HeatmapConfig
  ) => {
    if (!heatmapLayer) return;
    heatmapLayer.setOptions({
      radius: newConfig.radius ?? mapConfig.radius,
      blur: newConfig.blur ?? mapConfig.blur,
      ...newConfig
    });
    // 更新下热力图的配置
    _radius.value = newConfig.radius ?? mapConfig.radius;
    _blur.value = newConfig.blur ?? mapConfig.blur;
    heatmapLayer.redraw();
  };

  // 切换热力图显示
  const toggleHeatmap = () => {
    heatmapVisible.value = !heatmapVisible.value;

    if (heatmapVisible.value) {
      heatmapLayer.addTo(map.value);
    } else {
      map.value.removeLayer(heatmapLayer);
    }
  };

  // 重置地图
  const resetMap = () => {
    if (!map.value) return;
    // 重置配置
    _radius.value = mapConfig.radius;
    _blur.value = mapConfig.blur;

    // 重新生成热力图层
    if (heatmapLayer.value) {
      create(initData);
    }

    // 重置视图
    map.value?.setView(mapConfig.center, mapConfig.zoom);

    // 确保热力图可见
    if (!heatmapVisible.value) {
      toggleHeatmap();
    }
  };
  const destroy = () => {
    console.log("destroy清理地图资源");
    if (heatmapLayer && map.value) {
      map.value.removeLayer(heatmapLayer);
      heatmapLayer = null;
    }
  };
  return {
    config,
    heatmapVisible,
    heatmapLayer,
    toggleHeatmap,
    resetMap,
    newCreate,
    create,
    updateConfig,
    update,
    destroy
  };
}
